package com.a.learning_keep.activity.login

import android.content.Intent
import android.os.Handler
import android.view.KeyEvent
import android.widget.Toast
import com.a.learning_keep.base.BaseActivity
import com.a.learning_keep.bean.LoginData
import com.a.learning_keep.databinding.ActivityLoginBinding
import com.a.learning_keep.base.post
import com.a.learning_keep.base.token
import kotlin.concurrent.thread

/**
 * 登录界面
 * */
class Login : BaseActivity<ActivityLoginBinding>() {

    var sta = false

    override fun getBind(): ActivityLoginBinding {
        return ActivityLoginBinding.inflate(layoutInflater)
    }

    override fun initView() {
        binding.loginBut.setOnClickListener {
            val s1 = binding.phoneUsername.text.toString()
            val s2 = binding.password.text.toString()
            var js = "{\n" +
                "\"phone\":\"$s1\",\n" +
                "\"password\":\"$s2\"\n" +
                "}"
            thread {
                val data = post("/user/register", js, LoginData::class.java)
                runOnUiThread {
//                    Log.e("TAG", "initView: " + data.code + data.msg + data.token + s1 + s2 + "******\n" + js)
//                    if (data.msg == "success") {
//                        token = data.token
//                        startActivity(
//                            Intent(context, MainActivity::class.java)
//                        )
//                    }
//                    Toast.makeText(context, data.msg, Toast.LENGTH_SHORT).show()
                }

            }
        }

        //跳转创建账户界面
        binding.create.setOnClickListener {
            startActivity(
                Intent(context, Register::class.java)
            )
        }
        //跳转忘记密码界面
        binding.forget.setOnClickListener {
            startActivity(
                Intent(context, ForgetPassword::class.java)
            )
        }

    }

    /**
     * 限制中途退出
     * */
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (event!!.action == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (!sta) {
                    Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show()
                    sta = true
                } else {
                    finishAffinity()
                    token = ""
                }
                Handler().postDelayed({
                    sta = false
                }, 1500)

            }
        }

        return true
    }
}